import { 
	_decorator, 
	Component, 
	Vec2, 
	CCFloat, 
	Vec3, 
	Prefab, 
	view, 
	input, 
	Input,
	EventKeyboard,
	KeyCode
} from "cc";
const { ccclass, property } = _decorator;

@ccclass("Plane")
export class Plane extends Component {
  @property(CCFloat)
  public moveSpeed: number = 100;

  private _moveDir: Vec2 = new Vec2(0, 0);

  start() {}

  update(deltaTime: number) {
    let offset = new Vec3(
      this._moveDir.x * deltaTime * this.moveSpeed,
      this._moveDir.y * deltaTime * this.moveSpeed,
      0
    );
    this.node.position = this.node.position.add(offset);

    let winSize = view.getVisibleSize();
    if (this.node.position.x > winSize.width / 2) {
      this.node.position = new Vec3(winSize.width / 2, this.node.position.y);
    }

    if (this.node.position.x < -winSize.width / 2) {
      this.node.position = new Vec3(-winSize.width / 2, this.node.position.y);
    }

    if (this.node.position.y > winSize.height / 2) {
      this.node.position = new Vec3(this.node.position.x, winSize.height / 2);
    }

    if (this.node.position.y < -winSize.height / 2) {
      this.node.position = new Vec3(this.node.position.x, -winSize.height / 2);
    }
  }

  move(dir: Vec2) {
    this._moveDir.add(dir);
  }
  
  onLoad() {
	input.on(Input.EventType.KEY_DOWN, this._onKeyDown, this);
    input.on(Input.EventType.KEY_UP, this._onKeyUp, this);
  }
  
  private _onKeyDown(event: EventKeyboard) {
    switch (event.keyCode) {
      case KeyCode.KEY_W:
        this.move(new Vec2(0, 1));
        break;
      case KeyCode.KEY_S:
        this.move(new Vec2(0, -1));
        break;
      case KeyCode.KEY_A:
        this.move(new Vec2(-1, 0));
        break;
      case KeyCode.KEY_D:
        this.move(new Vec2(1, 0));
        break;
      default:
        break;
    }
  }

  private _onKeyUp(event: EventKeyboard) {
    switch (event.keyCode) {
      case KeyCode.KEY_W:
        this.move(new Vec2(0, -1));
        break;
      case KeyCode.KEY_S:
        this.move(new Vec2(0, 1));
        break;
      case KeyCode.KEY_A:
        this.move(new Vec2(1, 0));
        break;
      case KeyCode.KEY_D:
        this.move(new Vec2(-1, 0));
        break;
      default:
        break;
    }
  }
}
